'''
Created on 27/03/2011

@author: bruno
'''
import Database

session = Database.Session()

class Repository():


    '''
        @summary: Generic repository to handle database interactions

    '''

    def getAll(self,object):
        '''
            @summary: Return a list of instances of all elements in the table and return as a list

            @param: : Object to look for
            @return: list of objects
        '''
        try:
            return session.query(object).all()
        except:
            return []

    def get(self,object,id):

        '''
            @summary: Return an instance of the object based on the given identifier

            @param: : object and ident
            @return: intance of the object
        '''
        try:
            return session.query(object).get(id)
        except:
            return None


    def add(self,object):
        '''
            @summary: Add an object to the database

            @param: : object
            @return: true (inserted) or false (error)
        '''
        try:
            session.add(object)
            return True
        except:
            return False

    def add_or_update(self,object):
        '''
            @summary: Add or update an object to the database

            @attention: the update part needs to be tested

            @param: : object
            @return: true (inserted) or false (error)
        '''
        try:
            song =self.getById(object.id)
            if( song is None ):
                session.add(object)
            else:
                self.persist()

            return True
        except:
            return False

    def get_by(self,object,attribute,value):
        '''
            @summary: Get a list of instances of the object, matching the given attribute and value

            @param: : object, attribute and value
            @return: list of objects
        '''
        try:
            return session.query(object).filter(attribute+'=:val').params(val=value).all()
        except:
            return []


    def persist(self):
        '''
            @summary: Commit the session
        '''

        if( not Database.autocommit):
            try:
                session.commit()
            except:
                raise Exception



class MusicRepository(Repository):
    '''
        @summary: Specific actions for Music class

    '''
    pass

